<?php
namespace App\Services;

use App\Model\PaperQuestion;
use App\Model\UserPaper;
use App\Repositories\DailyAnswerQuestionRepository;
use App\Repositories\DailyAnswerRepository;
use App\Repositories\PaperQuestionRepository;
use App\Repositories\PaperRepository;
use App\Repositories\QuestionRepository;
use App\Repositories\SysConfigRepository;
use App\Repositories\UserPaperAnswerRepository;
use App\Repositories\UserPaperRepository;
use App\Traits\ReturnTrait;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class PaperService
{
    use ReturnTrait;

    /**
     * @Inject
     * @var AccountService
     */

    public $account_service;

    public function submit($params,$user){
        $id = $params['id'];
        $paper = PaperRepository::getInstance()->getById($id);
        $paper_question_num = PaperQuestion::query()->where('paper_id',$id)->where('score','>',0)->count('id');
        if(!$paper){
            return $this->error('问卷不存在');
        }
        //每个社区提交25份问卷
        $count_num = UserPaper::query()->where('community_id',$params['community_id'])->count('id');
        if($count_num>=25){
            return $this->error('该社区已提交25份问卷');
        }
        /**
         * 查看是否已提交 一户一个问卷
         */
//        $is_exists = UserPaper::query()->where('community_id',$params['community_id'])
//            ->where('build_no',$params['build_no'])
//            ->where('unit_no',$params['unit_no'])
//            ->where('house_no',$params['house_no'])
//            ->where('paper_id',$id)
//            ->first();
//        if($is_exists){
//            return $this->error('该户已提交过问卷');
//        }
        /**
         * [['id'=>1,'answer_txt'=>'A']]
         */
        $questions = json_decode($params['questions'],true);
        if(count($questions)<$paper_question_num){
            return $this->error('问题未作答完');
        }
        DB::beginTransaction();
        try{
            $result = UserPaperRepository::getInstance()->store([
                'user_id' => $user->id,
                'paper_id' => $id,
                'district_id' => $params['district_id'],
                'street_id'=> $params['street_id'],
                'community_id'=> $params['community_id'],
                'full_address'=>$params['area'].$params['street'].$params['community'],
                'build_no'=> isset($params['build_no'])?$params['build_no']:'',
                'unit_no'=> isset($params['unit_no'])?$params['unit_no']:'',
                'house_no'=>isset($params['house_no'])?$params['house_no']:'',
                'mask' => isset($params['mask'])?$params['mask']:null,
                'question_num' => $paper_question_num
            ]);
            if(!$result['success']){
                throw new \Exception('问卷保存失败');
            }
            $user_paper = $result['data'];
            $score=0;
            foreach ($questions as $item){
                $question = PaperQuestionRepository::getInstance()->getById($item['id']);
                $insert_data=[
                    'user_paper_id' => $user_paper->id,
                    'question_id' => $item['id'],
                    'paper_id' => $id,
                    'answer_txt' => $item['answer_txt'],
                    'question_title' => $question->title,
                    'question_answers' =>json_encode($question->answers),
                    'question_right_result' => $question->right_result,
                    'question_type' => $question->type,
                    'score' => $question->score,
                ];
                if($question->type==PaperQuestion::TYPE_INPUT){
                    $insert_data['is_answer_right']=1;
                    $score+=$question->score;
                }else{
                    if($question->right_result==$item['answer_txt']){
                        $insert_data['is_answer_right'] = 1;
                        $score+=$question->score;
                    }else{
                        $insert_data['is_answer_right'] = 0;
                    }
                }
                $result_answer = UserPaperAnswerRepository::getInstance()->store($insert_data);
                if(!$result_answer['success']){
                    throw new \Exception('题目保存失败');
                }
            }
            $user_paper->all_score = $score;
            if(!$user_paper->save()){
                throw new \Exception('分数保存失败');
            }
            DB::commit();
        }catch(\Throwable $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success([
            'paper' => $user_paper,
        ]);
    }

}